<template>
  <div class="withdraw">
      <bind-mobile v-if="!user.telephone"></bind-mobile>

      <div class="withdraw__form"
           v-else
      >
        <withdraw-progress
          v-if="isInProgress"
          :last-status="lastStatus"
          @refresh-status="refreshStatus"
        ></withdraw-progress>

        <el-form :model="form" ref="form" :rules="rules"
                 :disabled="loading"
                 v-else
                 label-position="top"
                 @submit.native.prevent="submit"
        >
          <el-row type="flex" justify="space-between" class="withdraw__header">
            <el-col :span="6" class="withdraw__header-item">
              <div class="withdraw__header-item-title">账户余额:</div>
              <div class="withdraw__header-amount">
                <svg-icon icon-class="withdraw" type="primary"></svg-icon>
                <!--{{ user.balance || 0 | currency}}-->
                {{ user.balance<0 ? 0 : user.balance | currency }}
              </div>
            </el-col>
            <el-col :span="10" class="withdraw__header-item withdraw__header-item--center">
              <el-button type="link" @click="updateAllBalance">
                <svg-icon class="pointer" icon-class="refresh" type="primary"
                          size="small"></svg-icon> 刷新
              </el-button>

              <el-button type="primary" @click="clearScore" v-if="isCreditUp">清算会员上分</el-button>

            </el-col>
            <!--<el-col :span="6" v-if="isCreditUp" class="withdraw__header-item">-->
              <!--<div class="withdraw__header-item-title">剩余上分额度:</div>-->
              <!--<div class="withdraw__header-amount">-->
                <!--<svg-icon icon-class="credit-up" type="primary"></svg-icon>-->
                <!--{{creditStatus.validAllocateAmount | currency}}-->
              <!--</div>-->
            <!--</el-col>-->
            <!--<el-col :span="6" class="withdraw__header-item withdraw__header-item&#45;&#45;center">-->
              <!--<el-button type="link" @click="updateAllBalance">-->
                <!--<svg-icon class="pointer" icon-class="refresh" type="primary"-->
                          <!--size="small"></svg-icon> 刷新-->
              <!--</el-button>-->
            <!--</el-col>-->
          </el-row>
          <el-row type="flex" justify="space-between" class="withdraw__header">
            <el-col :span="6" v-if="isCreditUp || isCreditUpAgent" class="withdraw__header-item">
              <div class="withdraw__header-item-title">上分总额:</div>
              <div class="withdraw__header-amount">
                <svg-icon icon-class="credit-up-total" type="primary"></svg-icon>
                {{creditStatus.amount | currency}}
              </div>
            </el-col>
            <el-col :span="6" v-if="isCreditUp" class="withdraw__header-item">
              <div class="withdraw__header-item-title">会员上分:</div>
              <div class="withdraw__header-amount">
                <svg-icon icon-class="credit-up-member" type="primary"></svg-icon>
                {{creditStatus.payOutAmount | currency}}
              </div>
            </el-col>
            <el-col :span="6" v-if="isCreditUpAgent" class="withdraw__header-item">
              <div class="withdraw__header-item-title">代理上分:</div>
              <div class="withdraw__header-amount">
                <svg-icon icon-class="credit-up-agent" type="primary"></svg-icon>
                {{creditStatus.proxyCreditedAmount | currency}}
              </div>
            </el-col>
            <el-col :span="6" v-if="isCreditUp || isCreditUpAgent" class="withdraw__header-item">
              <div class="withdraw__header-item-title">剩余上分:</div>
              <div class="withdraw__header-amount">
                <svg-icon icon-class="credit-up" type="primary"></svg-icon>
                {{creditStatus.validAllocateAmount | currency}}
              </div>
            </el-col>
          </el-row>

          <div class="withdraw__name"
               v-if="!cardList.length"
          >
            <el-form-item
              label="姓名："
              prop="name"
            >
              <el-input class="withdraw__input" v-model="form.name" :disabled="!!withdrawInfo.name" placeholder="请输入提款人姓名">
                <template slot="prepend">
                  <svg-icon class="withdraw__svg-prepend" icon-class="user"></svg-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-tip>为了资金安全考虑，姓名填写后无法再次更改</el-tip>
          </div>

          <el-form-item prop="cardId" v-if="cardList.length">
            <template slot="label">
              <span class="withdraw__label-name">选择提现银行卡：</span>
            </template>
            <el-select v-model="form.cardId"
                       class="withdraw__bank-select"
                       @change="cardChange"
            >
              <template slot="prefix">
                <bank-pic :bank-id="currentBankId"></bank-pic>
              </template>
              <el-option
                v-for="item in cardList"
                class="withdraw__bank-option"
                :label="item.bankName+' '+item.cardNo"
                :value="item.cardId"
                :key="item.cardId"
              >
                <bank-pic :bank-id="item.bankId"></bank-pic>
                {{item.bankName}} {{item.cardNo}}
              </el-option>
            </el-select>
            <el-button class="withdraw__label-btn" size="small" type="text" @click="gotoBindCard">新增/修改银行卡&nbsp;&nbsp;&nbsp;></el-button>
            <el-input v-model="form.name" style="display: none"></el-input>
          </el-form-item>

          <el-form-item class="withdraw__input" prop="cardNo" label="银行卡：" v-else>
            <el-input v-model="form.cardNo" placeholder="请输入您的银行卡号">
              <template slot="prepend">
                <svg-icon class="withdraw__svg-prepend" icon-class="m-recharge"></svg-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="withdraw__input withdraw__inline" prop="amount" label="金额：" v-if="withdrawConfig" :error="formError">
            <el-input
              class="withdraw__amount"
              type="number"
              v-model.number="form.amount"
              placeholder="请输入您的提现金额">
              <template slot="prepend">
                <svg-icon class="withdraw__svg-prepend" icon-class="withdraw"></svg-icon>
              </template>
              <template slot="append"><span class="text-black">元</span></template>
            </el-input>
            <!--<div class="withdraw__config">-->
              <!--<div class="withdraw__config-inner">-->
                <!--<div class="withdraw__config-label">-->
                  <!--单次提现：-->
                <!--</div>-->
                <!--<div class="withdraw__config-main">-->
                  <!--最低 {{withdrawConfig.minLimit}} - 最高 {{withdrawConfig.maxLimit}}-->
                <!--</div>-->

                <!--<div class="withdraw__config-label">-->
                  <!--每日提款：-->
                <!--</div>-->
                <!--<div class="withdraw__config-main">-->
                  <!--{{withdrawConfig.amountLimit}}-->
                <!--</div>-->
                <!--&lt;!&ndash;<div class="withdraw__config-label">&ndash;&gt;-->
                  <!--&lt;!&ndash;每日免费提现：&ndash;&gt;-->
                <!--&lt;!&ndash;</div>&ndash;&gt;-->
                <!--&lt;!&ndash;<div class="withdraw__config-main">&ndash;&gt;-->
                  <!--&lt;!&ndash;{{withdrawConfig.freeTimes}}次&ndash;&gt;-->
                <!--&lt;!&ndash;</div>&ndash;&gt;-->
              <!--</div>-->
            <!--</div>-->
          </el-form-item>
          <div class="withdraw__explain">
            <el-popover
              placement="top"
              title="提现说明"
              width="450"
              trigger="hover">
              <div class="retain-page__tip">
                <!--<div class="retain-page__tip-title">普通到账说明</div>-->
                <div class="retain-page__tip-content">
                  1.每次提现均会收取{{withdrawInfo.proxyConfig.feeType == "fix" ? withdrawInfo.proxyConfig.fee + '元' : withdrawInfo.proxyConfig.fee + '%'}}的手续费。<br>
                  2.当日提现次数限制{{withdrawInfo.proxyConfig.countLimit}}次，达到提现次数后，当日无法提现。<br>
                  3.当日提现金额上限为{{withdrawInfo.proxyConfig.amountLimit}}元，达到提现金额上限后，当日无法再次进行提现。<br>
                  <!--4.单笔提现限额{{withdrawInfo.proxyConfig.minLimit + '~' + withdrawInfo.proxyConfig.maxLimit}}元，超过本金额的提现，系统默认拆成多笔提现订单。<br>-->
                  4.提现金额超过{{withdrawInfo.proxyConfig.maxLimit}}元时，系统默认拆成多笔提现订单。<br>
                  5.当日是指00:00~24:00时间段。<br><br>
                </div>
                <!--<div class="retain-page__tip-title">大额提现说明</div>-->
                <!--<div class="retain-page__tip-content">-->
                  <!--1.当日提现次数上限至{{withdrawInfo.quickConfig.countLimit}}次，达到提现次数后，当日无法进行提现。<br>-->
                  <!--2.当日提现金额上限至{{withdrawInfo.quickConfig.amountLimit}}元，达到提现金额上限后，当日无法进行提现。<br>-->
                  <!--3.单笔提现限额{{withdrawInfo.quickConfig.minLimit + '~' + withdrawInfo.quickConfig.maxLimit}}元，超过本金额的提现，系统默认拆成多笔充值订单。<br>-->
                  <!--4.当日是指00:00~24:00时间段。-->
                <!--</div>-->
              </div>
              <div slot="reference">
                <i class="el-icon-warning"></i> 提现说明
              </div>
            </el-popover>
          </div>

          <!--<el-form-item v-if="withdrawConfig && withdrawConfig.freeTimes <= withdrawInfo.withdrawTimes">-->
            <!--<div>-->
              <!--手续费：{{feeGrid.totalFee}}元-->
            <!--</div>-->
            <!--<div>-->
              <!--实际到账：{{feeGrid.total | currency}}元-->
            <!--</div>-->
          <!--</el-form-item>-->
          <el-form-item v-if="withdrawConfig">
            <div>
              手续费：{{feeGrid.totalFee}}元
            </div>
            <div>
              实际到账：{{feeGrid.total | currency}}元
            </div>
          </el-form-item>
          <el-form-item class="withdraw__submit">
            <el-button type="primary" block native-type="submit" :disabled="!canWithdraw">确认提现</el-button>
            <div v-if="!canWithdraw" class="text-danger">{{errorTip}}</div>
          </el-form-item>
        </el-form>
        <!-- 提现中结束 -->

      </div>
    <div v-transfer-dom>
      <el-dialog :visible.sync="dialogVisible" :before-close="() => {dialogVisible = false}" :title="dialogTitle"
                 :width="consts.DIALOG_SIZE_NORMAL">
        <component :is="dialogName"
            :withdraw-data="dialogProps"
            @on-success="dialogSubmitSuccess"
            @on-close="dialogVisible = false"
            v-if="dialogName"
        ></component>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {factory, form, updateBalance, dialog} from '@/build';
  import {getWithdrawInfo, getWithdrawStatus, submitWithdraw} from '@/services/api/finance';
  import BindMobile from "./bind-mobile";
  import WithdrawProgress from "./withdraw-progress";
  import WithdrawValidate from './withdraw-validate';
  import UpperScoreClear from './upper-score-clear';

  export default {
    name: "finance-withdraw",

    mixins: [form, factory, updateBalance, dialog],

    components: {
      WithdrawProgress,
      BindMobile,
      WithdrawValidate,
      UpperScoreClear,
    },

    data() {
      const checkAmount = (rule, value, callback) => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数'));
        } else {
          if (value < this.withdrawConfig.minLimit) {
            callback(new Error(`单笔提现金额最小为${this.withdrawConfig.minLimit}`));
          } else if (value > this.withdrawConfig.maxLimit) {
            callback(new Error(`单笔提现金额最大为${this.withdrawConfig.maxLimit}`));
          } else {
            callback();
          }
        }
      };
      return {
        isInProgress: false,
        form: {
          name: undefined,
          amount: undefined,
          cardNo: undefined,
          cardId: undefined,
        },

        withdrawInfo: {
          freeTimes: 0,
          proxyConfig: {
            feeType: 'fix',
            fee: 0,
            countLimit: 0,
            amountLimit: 0,
            minLimit: 0,
            maxLimit: 0,
          }
        },
        isInit: true,
        isCurrentInProgress: false,
        lastStatus: {},
        formError: '',
        rules: {
          cardNo: factory.getRule('cardNumber'),
          // amount: factory.getRule('money'),
          amount: [
            {required: true, message: '请输入您的提现金额'},
            {validator: checkAmount, trigger: 'blur'}
          ],
          cardId: {required: true, message: '银行卡为必选'},
          name:{required: true, message: '姓名为必选'}
        },
        canWithdraw:true,
        errorTip:'',
        // checkStep: 0,
      };

    },
    watch: {
      lastStatus:{
        handler(newValue, oldValue){
          this.check(newValue);
        }
      }
    },
    computed: {
      ...mapState({
        user: state => state.user,
        creditStatusAgent: state => state.creditStatusAgent
      }),
      creditStatus(){
        // 把对象引用地址改变一下， 不然页面不更新
        const data = {...this.$store.state.creditStatus};
        return data;
      },
      ...mapGetters([
        'isCreditUp',
        'isCreditUpAgent',
      ]),
      currentBankId() {
        if (this.form.cardId) {
          const currentCardInfo = _.find(this.withdrawInfo.cardList, {'cardId': this.form.cardId});
          return currentCardInfo ? currentCardInfo.bankId : undefined;
        } else {
          return undefined;
        }
      },
      withdrawConfig() {
        return this.withdrawInfo.proxyConfig;
      },
      cardList() {
        return this.withdrawInfo.cardList || [];
      },
      // isInProgress() {
      //   if(_.isArray(this.lastStatus)){
      //     _.each(this.lastStatus, (item) => {
      //       return this.checkIsInProgress(item.status) || this.isCurrentInProgress;
      //     })
      //     // return this.checkIsInProgress(this.lastStatus[0].status) || this.isCurrentInProgress;
      //   }
      //
      // },

      feeGrid() {
        const {feeType} = this.withdrawConfig;
        const {amount} = this.form;
        let totalFee = 0;

        if (_.isUndefined(amount)) {
          return {
            totalFee,
            type: this.withdrawConfig.fee + (feeType === 'percent' ? '%' : '元'),
            total: 0
          };
        }
        let total = 0;
        if (feeType === 'percent'){
          total = amount * this.withdrawConfig.fee / 100 || 0;

          totalFee = total > this.withdrawConfig.feeLimit ? this.withdrawConfig.feeLimit : total;
        }else {
          total = this.withdrawConfig.fee || 0;

          totalFee = total;
        }
        // const total = amount * this.withdrawConfig.fee / 100 || 0;

        // if (this.withdrawConfig.freeTimes) {
        //   if (this.withdrawInfo.withdrawTimes >= this.withdrawConfig.freeTimes) {
        //     totalFee = total > this.withdrawConfig.feeLimit ? this.withdrawConfig.feeLimit : total;
          // }
        // }

        let fee = this.withdrawConfig.fee;
        if (feeType === 'percent') {
          return {
            totalFee,
            // type: this.withdrawConfig.fee + '%',
            type: fee + '%',
            total: amount - totalFee
          };
        }else {
          // if (fee>this.withdrawConfig.feeLimit){
          //   fee = this.withdrawConfig.feeLimit
          // }
          return {
            totalFee,
            // type: this.withdrawConfig.fee + '元',
            // total: amount - this.withdrawConfig.fee<0?0:amount - this.withdrawConfig.fee
            type: fee + '元',
            // total: amount - fee<0?0:amount - fee
            total: amount - totalFee<0?0:amount - totalFee
          };
        }

        // return {
        //   totalFee,
        //   type: this.withdrawConfig.fee + '元',
        //   total: amount - this.withdrawConfig.fee
        // };
      }
    },
    methods: {
      check(data) {
        if(_.isArray(data)) {
          _.each(data, (item) => {
            if(_.includes([
                ...consts.WITHDRAW_STATUS_AUDIT_ING,
                ...consts.WITHDRAW_STATUS_PAYMENT_OUT_ING,
              ], item.status)) {
              this.isInProgress = true;
            }
            // return this.checkIsInProgress(item.status) || this.isCurrentInProgress;
          });
        }
      },
      clearScore(){
        if(this.user.status != 0 && this.user.status != -1){
          this.$message({
            type : 'warning',
            message: '该账户已锁定，无法进行清算'
          });
          return;
        }
        this.updateAllBalance();
        this.openDialog({dialogName: 'upper-score-clear',})
      },
      updateAllBalance() {
        this.updateBalance();
        // this.$store.dispatch(types.GET_CREDIT_STATUS);
      },
      gotoBindCard() {
        this.$router.push('/safety?sub=safety-card-bind');
      },
      checkIsInProgress(status) {
        return _.includes([
          ...consts.WITHDRAW_STATUS_AUDIT_ING,
          ...consts.WITHDRAW_STATUS_PAYMENT_OUT_ING,
        ], status);
      },
      submit() {
        if (this.withdrawInfo.needSms) {
          this.$refs.form.validate().then(() => {
            this.openDialog({
              dialogName: 'withdraw-validate',
              props: this.form
            });
          });
        } else {
          this.doSave({action:'saveForm',form:'form'});
        }
      },
      refreshStatus() {
        this.doGet({action: 'getWithdrawStatus'});
      },

      dialogSubmitSuccess(data) {
        this.dialogVisible = false;
        this.$_submitSuccess(data);
      },
      $_submitSuccess(data) {
        this.isCurrentInProgress = true;
        this.resetForm('form');
        this.lastStatus = data;
        this.$store.dispatch(types.OAUTH);
      },
      cardChange() {
        // console.log(this.form.cardId)
        const formInfo = _.find(this.withdrawInfo.cardList, {'cardId': this.form.cardId});
        // console.log(formInfo)
        this.form.name = formInfo.name;
      }
    },
    mounted() {
      if (this.user.telephone) {
        this.bindGet(getWithdrawInfo, 'withdrawInfo', {
          format: data => {
            // this.form.name = data.name;

            //默认选中银行卡
            if (data.cardList) {
              const defaultSelectCard = _.find(data.cardList, {selected: 1});
              if (defaultSelectCard) {
                this.form.cardId = defaultSelectCard.cardId;
                this.form.name = defaultSelectCard.name;
              }
            }
            if(data.proxyConfig.withdrawCount >= data.proxyConfig.countLimit){
              this.canWithdraw = false;
              this.errorTip = `当日提现次数已达上限！当日提现次数：${data.proxyConfig.countLimit}`;
            }
            if(data.proxyConfig.amountLimit > 0 && data.withdrawSumAmount > 0 && data.withdrawSumAmount >= data.proxyConfig.amountLimit){
              this.canWithdraw = false;
              this.errorTip = `当日提现金额已达上限！当日提现金额上限：${data.proxyConfig.amountLimit}`;
            }
            return data;
          }
        });

        this.bindGet(getWithdrawStatus, 'lastStatus', {
          action: 'getWithdrawStatus',
          format:(data) => {
            if (!data) {
              return {};
            } else {
              if (this.isInit && this.checkIsInProgress(data.status)) {
                this.isCurrentInProgress = true;
              }
              this.isInit = false;
              // this.lastStatus = data;
              return data;
              // this.check()
            }
          }
        });

        this.doGet({action: getWithdrawInfo.name});
        this.doGet({action: getWithdrawStatus.name});
      }


      this.bindSave(submitWithdraw, 'saveForm', 'form',
        {
          beforeSend: (data) => {
            // console.log(data);
            this.formError = '';
            return data;
          },
          successMessage: '提现申请成功',
          errorMessage: '提现申请失败.',
          afterSuccess: ([result, data]) => {
            if (result) {
              this.$_submitSuccess(data);
            }
          },
          afterFail: ([result, data]) => {
            this.formError = data.message;
          }
        }
      );
    },
  };
</script>

<style lang="scss">
  $--font-title-color: #000000;
  $--tip-color: #999999;

  @include b(withdraw) {
    @include main-center(900px);

    border-radius: $--border-radius-base;
    border:$--border-base;
    box-sizing: border-box;
    /*padding: 40px 133px;*/
    padding: 40px 50px;

    @include e(header) {
      padding-bottom: 30px;
      margin-bottom: 10px;
      border-bottom: $--border-base;
    }
    @include e(header-item) {
      font-size: 16px;

      @include m(center) {
        display: flex;
        align-items: center;
      }
      &.withdraw__header-item--center {
        justify-content: flex-end;
        .el-button--primary{
            margin-left: 0.3rem;
            background: #1E5ADC;
            border-radius: 8px;
            width: 181px;
            height: 50px;
        }
      }
      
    }
    @include e(header-item-cell) {
      font-size: 16px;
    }

    @include e(header-amount) {
      font-size: 24px;
      font-weight: bold;
      margin-top: 4px;
      .svg-icon {
        width:22px;
        height:22px;
        margin-right: 6px;
      }
    }


    @include e(input) {
      width: 300px;
      /*display: inline-block;*/
    }
    @include e(inline) {
    /*width: 300px;*/
    display: inline-block;
  }
    @include e(bank-select) {
      width: 320px;
    }

    @include e(submit) {
      margin-top: 50px;
      width: 300px;
    }

    @include e(bank-select) {
      .el-form-item__label {
        display: block;
      }
    }
    @include e(label-btn) {
      margin-left: 30px;
      vertical-align: top;
      margin-top: 10px;
    }

    @include e(name) {
      display: flex;
      align-items: flex-end;
      .el-tip {
        flex: 1;
        margin-left: 30px;
        margin-bottom: 22px;
      }

    }

    @include e(amount) {
      width: 320px;
    }
    @include e(explain) {
      display: inline-block;
      margin-left: 30px;
      color: $--color-danger;
    }

    @include e(config) {
      background-color: $--color-white;
      border-radius: $--border-radius-base;
      border: 1px solid $--color-black;
      margin-left: 27px;
      position: absolute;
      top: -30px;
      right: -240px;
      box-shadow: 0px 12px 32px 0px rgba(0, 0, 0, 0.12);
      line-height: 20px;
      &:before {
        position: absolute;
        left: -10px;
        top: 44px;
        display: block;
        width: 20px;
        height: 20px;
        border: 1px solid $--color-black;
        background-color: $--color-white;
        content: '';
        transform: rotate(45deg);
        z-index: 1;
      }
    }
    @include e(config-inner) {
      background-color: $--color-white;
      border-radius: $--border-radius-base;
      padding: 16px;
      position: relative;
      z-index: 1;
      width: 180px;
      box-sizing: border-box;
    }
    @include e(config-label) {
      font-weight: bold;
    }
    @include e(config-main) {
      margin-bottom: 6px;

      &:last-of-type {
        margin-bottom: 0;
      }
    }

    @include e(svg-prepend) {
      &.svg-icon {
        width: 22px;
        height: 22px;
      }
    }

    @include e(payment-option) {
      height: 50px;
      line-height: 50px;
      display: flex;
      align-items: center;
      .payment-pic {
        margin-right: 10px;
      }
    }

    @include e(main) {
      min-height: 200px;
    }

    @include e(bank-option) {
      height: 50px;
      line-height: 50px;
      display: flex;
      align-items: center;
      .bank-pic {
        margin-right: 10px;
      }
    }
  }
</style>
